const fs = require('fs');
const path = require('path');
const UUID = require('node-uuid');
const mime = require('mime-types');
const pushUtils = require('../../utils/push');
const wxPushUtils = require('../../utils/wxPush');
const systemRouter = {
    prefix: '/system',
    routers: [{
            method: 'get',
            url: '/message',
            handler: async(ctx, next) => {
				await wxPushUtils.batchPush('oLxbF5AJGOIAqw6yzGQSZttZnhhA')
                /* await pushUtils.batchPush(['810f8cf6e89a24d6b0959e886c6ce231'], {
                    title: '您有新的订单',
                    body: '矿泉水、红薯、牛奶'
                }) */
                ctx.body = {
                    code: 1,
                    msg: '操作成功！'
                }
            }
        },
        {
            method: 'post',
            url: '/upload',
            handler: async(ctx, next) => {
                const file = ctx.request.files.file;
                const reader = fs.createReadStream(file.path);
                let filename = file.name;
                filename = UUID.v1() + filename.substring(filename.lastIndexOf('.'), filename.length)
                let filePath = path.join(__dirname, '../../public/upload/tmp') + `/${filename}`;
                try {
                    const upStream = fs.createWriteStream(filePath);
                    reader.pipe(upStream);
                    console.log('已成功写入文件');
                } catch (e) {
                    return ctx.body = {
                        code: 1,
                        msg: '上传失败！',
                        data: {
                            filename
                        }
                    }
                }
                ctx.body = {
                    code: 1,
                    msg: '上传成功！',
                    data: {
                        filename
                    }
                }
            }
        },
        {
            method: 'get',
            url: '/image/:catalog/:url',
            handler: async(ctx, next) => {
                const url = ctx.params.url;
                const catalog = ctx.params.catalog;
                let filePath = path.join(__dirname, '../../public/upload/') + catalog + '/' + url;
                let file = null;
                try {
                    file = fs.readFileSync(filePath);
                } catch (e) {
                    console.error('图片不存在');
                }
                let mimeType = mime.lookup(filePath);
                ctx.set('content-type', mimeType);
                ctx.body = file;
            }
        }
    ]
}

module.exports = systemRouter;